package com.manli.api.base.beetlsql;

import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author shensg
 */
@Component
public class BaseDaoManager {

    @Autowired
    SQLManager sqlManager;


    public <T> PageQuery<T> execute(SQLReady p, Class<T> clazz, PageQuery<T> pageQuery) {
        if (pageQuery.getParas() != null) {
            throw new RuntimeException("参数需要通过SQLReady传递");
        }
        String sql = p.getSql();
        String countSql = this.getCountSql(sql);
        SQLReady countSqlReady = new SQLReady(countSql);
        List<T> list = null;
        List<Long> countList = sqlManager.execute(countSqlReady, Long.class);
        Long count = countList.get(0);
        if (count == 0) {
            list = Collections.emptyList();
        } else {
            long pageNumber = pageQuery.getPageNumber();
            long pageSize = pageQuery.getPageSize();
            long offset = (pageNumber - 1) * pageSize ;
            String pageSql =p.getSql() + " limit " + offset +" , "+ pageSize;
            SQLReady pageSqlReady = new SQLReady(pageSql);
            list = sqlManager.execute(pageSqlReady,clazz);
        }
        pageQuery.setTotalRow(count);
        pageQuery.setList(list);
        return pageQuery;
    }

    public String getCountSql(String selectSql) {

        /*selectSql = PageKit.formatSql(selectSql);
        String sql = selectSql.toLowerCase();

        // 是否存在最外层 order by
        int orderByIndex = sql.indexOf("\n    order by");
        //最外层的from
        int fromIndex = sql.indexOf("\n    from") ;
        // 存在order by 就移除
        if (orderByIndex!=-1) {
            return "select count(1) \n" + selectSql.substring(fromIndex, orderByIndex);
        }
        //简单的改成count
        return "select count(1) \n" + selectSql.substring(fromIndex);*/

        return "select count(1) from ("+ selectSql +") countTable ";
    }

    public static void main(String[] args) {
        //System.out.println(ManliSQLManager.getCountSql("select * from (select * from we_chat_user_info group by we_chat_user_info_id order by we_chat_user_info_id ) t"));
    }
}
